import React from 'react';
import { Breadcrumb } from 'antd';
import PropTypes from 'prop-types';
import { useLocation } from 'react-router-dom';

// 获取当前菜单
const getCurrMenu = (list, link) => {
  let currMenu = [];

  list.forEach((item) => {
    if (item.link && item.link === link) {
      currMenu = [
        {
          key: item.key,
          name: item.name,
        },
      ];
    } else if (item.children) {
      item.children.forEach((subItem) => {
        if (subItem.link && subItem.link === link) {
          currMenu = [
            {
              key: item.key,
              name: item.name,
            },
            {
              key: item.key,
              name: subItem.name,
            },
          ];
        }
      });
    }
  });

  return currMenu;
};

const BreadcrumbComp = ({ menuList }) => {
  const location = useLocation();
  const currMenu = getCurrMenu(menuList, location.pathname);

  return (
    <Breadcrumb style={{ margin: '16px 0' }}>
      {currMenu.map((menu) => (
        <Breadcrumb.Item key={menu.key}>{menu.name}</Breadcrumb.Item>
      ))}
    </Breadcrumb>
  );
};

BreadcrumbComp.propTypes = {
  menuList: PropTypes.arrayOf(PropTypes.object),
};

export default BreadcrumbComp;
